const express = require('express')
const router = express.Router()
const { verifyToken } = require('../../middilWare/verifyToken')
const {
  createToken,
  getToken,
  updateToken,
  clearToken,
  getAllToken,
} = require('../../services/tokenService')

// 创建token
router.post('/', async (req, res) => {
  try {
    const { username, userType, token, expireTime } = req.body
    const result = await createToken(username, userType, token, expireTime)
    res.status(200).json({ code: 200, message: 'token created', data: result })
  } catch (error) {
    res.status(500).json({ code: 500, message: 'token create failed' })
  }
})

// 获取token
router.get('/', verifyToken, async (req, res) => {
  try {
    const { username } = req.query
    const result = await getToken(username)
    res.status(200).json({ code: 200, data: result })
  } catch (error) {
    res.status(500).json({ code: 500, message: 'get token failed' })
  }
})

// 更新token
router.put('/', verifyToken, async (req, res) => {
  try {
    const { username, token } = req.body
    const result = await updateToken(username, token)
    res.status(200).json({ code: 200, message: 'token updated', data: result })
  } catch (error) {
    res.status(500).json({ code: 500, message: 'token update failed' })
  }
})

// 删除token
router.delete('/', verifyToken, async (req, res) => {
  try {
    const { username } = req.body
    const result = await clearToken(username)
    res.status(200).json({ code: 200, message: 'token deleted', data: result })
  } catch (error) {
    res.status(500).json({ code: 500, message: 'token delete failed' })
  }
})

// 获取所有token
router.get('/all', verifyToken, async (req, res) => {
  try {
    const result = await getAllToken()
    res.status(200).json({ code: 200, data: result })
  } catch (error) {
    res.status(500).json({ code: 500, message: 'get all token failed' })
  }
})

module.exports = router
